package com.cnpc.framework.base.service.impl;

import com.beust.jcommander.IVariableArity;
import com.cnpc.framework.base.dao.BaseDao;
import com.cnpc.framework.base.entity.*;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.service.OrgService;
import com.cnpc.framework.base.service.UserRoleService;
import com.cnpc.framework.base.service.UserService;
import com.cnpc.framework.constant.RedisConstant;
import com.cnpc.framework.utils.EncryptUtil;
import com.cnpc.framework.utils.ExcelImportUtil;
import com.cnpc.framework.utils.PropertiesUtil;
import com.cnpc.framework.utils.StrUtil;
import com.google.gson.Gson;
import com.lc.entity.ItemChangeRecord;
import com.lc.entity.UserFile;
import com.lc.entity.UserTag;
import com.lc.entity.UserTagChange;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl implements UserService {

    @Resource
    private BaseDao baseDao;

    @Autowired
    OrgService orgService;

    private List<User> getUsers() {

        return baseDao.find("from User");
    }

    public void setRoleForRegisterUser(String userId) {
        String hql = "from Role where code='COMMON' and (deleted=0 or deleted is null)";
        Role role = this.get(hql);
        if (role != null) {
            UserRole userRole = new UserRole();
            User user = this.get(User.class, userId);
            userRole.setUser(user);
            userRole.setRoleId(role.getId());
            userRole.setDeleted(0);
            this.save(userRole);
        }

    }

    public void saveUserRoles(String userId,String roleIds) throws Exception{
        String sql = "delete from tbl_user_role where userId = :userId";
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        executeSql(sql,params);

        sql = "insert into tbl_user_role(id,create_date_time,update_date_time,version,deleted,roleId,userId)" +
                " values(:id,now(),now(),1,0,:roleId,:userId)";

        for (String roleId : roleIds.split(",")) {
            params.put("id",UUID.randomUUID().toString().replace("-",""));
            params.put("roleId",roleId);
            executeSql(sql,params);
        }

        redisDao.delete(userId);
        redisDao.delete(RedisConstant.ROLE_PRE+userId);
        redisDao.delete(RedisConstant.PERMISSION_PRE+userId);
    }

    @Override
    public Result editUserWithoutTags(User user) throws Exception {
        Result result = new Result();
        user.setSh("0");
        user.setShtime(null);
        user.setReason(null);
        user.setChangetype("基本信息变更");
        String edituser = user.getEdituser();
        String userId = user.getId();

        String databf = null;
        String dataaf = null;

        String roleIds= user.getRoleIds();
        if (StringUtils.isEmpty(roleIds)) {
            result.setSuccess(false);
            result.setMessage("角色不可空！");
            return result;
        }

        if (StrUtil.isEmpty(userId)) {

            String joinTime = user.getJoinTime();
            if (StringUtils.isEmpty(joinTime)) {
                result.setSuccess(false);
                result.setMessage("入职时间不可空！");
                return result;
            }
            if (StringUtils.isEmpty(user.getEmpno())) {
                String prefix = joinTime.replace("-", "").substring(0, 6);
                String sql = "select max(empno) from tbl_user where empno like :empno";
                Map<String, Object> params = new HashMap<>();
                params.put("empno", prefix + "%");
                String maxCode = getBySql(sql, params);
                String empno = StringUtils.isEmpty(maxCode) ? prefix + "01" : String.format("%08d", Integer.parseInt(maxCode) + 1);
                user.setEmpno(empno);
            }

            //设置初始密码
            user.setPassword(EncryptUtil.getPassword(PropertiesUtil.getValue("user.initPassword"), user.getLoginName()));

            user.setVersion(0);

            userId = save(user).toString();
            //setRoleForRegisterUser(userId);

            saveUserRoles(userId,roleIds);
        } else {
            User oldUser = getUserById(userId);
            String oldRoleIds = oldUser.getRoleIds();

            databf = new Gson().toJson(oldUser);

            if (StringUtils.isEmpty(oldUser.getEmpno()) && StringUtils.isNotEmpty(user.getJoinTime()) && StringUtils.isEmpty(user.getEmpno())) {
                String joinTime = user.getJoinTime();
                String prefix = joinTime.replace("-", "").substring(0, 6);
                String sql = "select max(empno) from tbl_user where empno like :empno";
                Map<String, Object> params = new HashMap<>();
                params.put("empno", prefix + "%");
                String maxCode = getBySql(sql, params);
                String empno = StringUtils.isEmpty(maxCode) ? prefix + "01" : String.format("%08d", Integer.parseInt(maxCode) + 1);

                oldUser.setEmpno(empno);
            }

            if (!oldUser.getLoginName().equals(user.getLoginName())) {
                oldUser.setPassword(EncryptUtil.getPassword(PropertiesUtil.getValue("user.initPassword"), user.getLoginName()));
            }

            BeanUtils.copyProperties(user, oldUser, "password", "createDateTime", "version", "token", "token_limit"
                    , "userTags0", "userTags1", "userTags2", "userTags3", "userTags4", "userTags5","userTags6","userFiles");
            oldUser.setUpdateDateTime(new Date());

            update(oldUser);

            if (!roleIds.equals(oldRoleIds)) {
                saveUserRoles(userId,roleIds);
            }

        }

        try {
            User nowUser = getUserById(userId);

            dataaf = new Gson().toJson(nowUser);

            ItemChangeRecord record = new ItemChangeRecord();
            record.setDefaultTime();
            record.setUserid(edituser);
            record.setType("item_change_type_user");
            record.setItemid(userId);
            record.setDatabf(databf);
            record.setDataaf(dataaf);
            record.setName(user.getName());
            record.setSubtype(StringUtils.isEmpty(databf) ? 0 : 1);
            save(record);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public Result editUser(User user) throws Exception {
        Result result = new Result();
        user.setSh("0");
        user.setShtime(null);
        user.setReason(null);
        user.setChangetype("个人信息变更");
        String edituser = user.getEdituser();
        String userId = user.getId();
        List<UserTag> saveList = new ArrayList<>();

        String databf = null;
        String dataaf = null;

        String initPwd = PropertiesUtil.getValue("user.initPassword");
        String joinTime = user.getJoinTime();
        if (StringUtils.isEmpty(joinTime)) {
            result.setSuccess(false);
            result.setMessage("入职时间不可空！");
            return result;
        }

       String idcard = user.getIdcard();
         /*if (StringUtils.isEmpty(idcard)) {
            result.setSuccess(false);
            result.setMessage("身份证号码不可空！");
            return result;
        }else if (idcard.length()<6){
            result.setSuccess(false);
            result.setMessage("身份证号码长度不正确！");
            return result;
        }else {
            int len = idcard.length();
            initPwd = idcard.substring(len-6,len);
        }*/

        String roleIds= user.getRoleIds();
        if (StringUtils.isEmpty(roleIds)) {
            result.setSuccess(false);
            result.setMessage("角色不可空！");
            return result;
        }

        boolean userRoleChange = false;
        if (StrUtil.isEmpty(userId)) {


            if (StringUtils.isEmpty(user.getEmpno())) {
                String prefix = joinTime.replace("-", "").substring(0, 6);
                String sql = "select max(empno) from tbl_user where empno like :empno";
                Map<String, Object> params = new HashMap<>();
                params.put("empno", prefix + "%");
                String maxCode = getBySql(sql, params);
                String empno = StringUtils.isEmpty(maxCode) ? prefix + "01" : String.format("%08d", Integer.parseInt(maxCode) + 1);
                user.setEmpno(empno);
            }else {
                String sql = "select count(*) from tbl_user where empno =:empno";
                Map<String, Object> params = new HashMap<>();
                params.put("empno", user.getEmpno());
                Long cnt = countBySql(sql, params);
                if (cnt>0) {
                    result.setSuccess(false);
                    result.setMessage("工号已存在！");
                    return result;
                }
            }

            if (StringUtils.isNotEmpty(idcard)) {
                String sql = "select count(*) from tbl_user where idcard =:idcard";
                Map<String, Object> params = new HashMap<>();
                params.put("idcard", idcard);
                Long cnt = countBySql(sql, params);
                if (cnt>0) {
                    result.setSuccess(false);
                    result.setMessage("身份证号码已存在！");
                    return result;
                }
            }

            //设置初始密码
            user.setPassword(EncryptUtil.getPassword(initPwd, user.getLoginName()));

            user.setVersion(0);

            userId = save(user).toString();
            //setRoleForRegisterUser(userId);
            saveUserRoles(userId,roleIds);
            userRoleChange = true;
        } else {
            User oldUser = getUserById(userId);
            String oldRoleIds = oldUser.getRoleIds();

            databf = new Gson().toJson(oldUser);

            if (StringUtils.isEmpty(oldUser.getEmpno()) && StringUtils.isNotEmpty(user.getJoinTime()) && StringUtils.isEmpty(user.getEmpno())) {
                String prefix = joinTime.replace("-", "").substring(0, 6);
                String sql = "select max(empno) from tbl_user where empno like :empno";
                Map<String, Object> params = new HashMap<>();
                params.put("empno", prefix + "%");
                String maxCode = getBySql(sql, params);
                String empno = StringUtils.isEmpty(maxCode) ? prefix + "01" : String.format("%08d", Integer.parseInt(maxCode) + 1);

                oldUser.setEmpno(empno);
            }else if (StringUtils.isNotEmpty(user.getEmpno())){
                String sql = "select count(*) from tbl_user where empno =:empno and id<>:id";
                Map<String, Object> params = new HashMap<>();
                params.put("empno", user.getEmpno());
                params.put("id", userId);
                Long cnt = countBySql(sql, params);
                if (cnt>0) {
                    result.setSuccess(false);
                    result.setMessage("工号已存在！");
                    return result;
                }
            }

            if (StringUtils.isNotEmpty(idcard)) {
                String sql = "select count(*) from tbl_user where idcard =:idcard and id<>:id";
                Map<String, Object> params = new HashMap<>();
                params.put("idcard", idcard);
                params.put("id", userId);
                Long cnt = countBySql(sql, params);
                if (cnt>0) {
                    result.setSuccess(false);
                    result.setMessage("身份证号码已存在！");
                    return result;
                }
            }

            if (!oldUser.getLoginName().equals(user.getLoginName())) {
                oldUser.setPassword(EncryptUtil.getPassword(initPwd, user.getLoginName()));
            }

            BeanUtils.copyProperties(user, oldUser, "password", "createDateTime", "version", "token", "token_limit"
                    , "userTags0", "userTags1", "userTags2", "userTags3", "userTags4", "userTags5","userTags6","userFiles");
            oldUser.setUpdateDateTime(new Date());

            update(oldUser);

            if (!roleIds.equals(oldRoleIds)) {
                //saveUserRoles(userId,roleIds);
                userRoleChange = true;
            }

            String sql = "delete from tbl_user_tag where userId=:userId";
            Map<String,Object> params = new HashMap<>();
            params.put("userId",userId);
            executeSql(sql,params);

            sql = "delete from tbl_user_file where userId=:userId";
            executeSql(sql,params);

        }

        if (user.getUserTags0() != null && user.getUserTags0().size() > 0) {
            for (int i = 0; i < user.getUserTags0().size(); i++) {
                UserTag userTag = user.getUserTags0().get(i);
                userTag.setSortno(i+1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType("0");
                saveList.add(userTag);
            }

        }

        if (user.getUserTags1() != null && user.getUserTags1().size() > 0) {
            List<UserTag> userTags = user.getUserTags1();
            for (int i = 0; i < userTags.size(); i++) {
                UserTag userTag = userTags.get(i);
                userTag.setSortno(i+1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType("1");
                saveList.add(userTag);
            }
        }

        if (user.getUserTags2() != null && user.getUserTags2().size() > 0) {
            List<UserTag> userTags = user.getUserTags2();
            for (int i = 0; i < userTags.size(); i++) {
                UserTag userTag = userTags.get(i);
                userTag.setSortno(i+1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType("2");
                saveList.add(userTag);
            }
        }

        if (user.getUserTags3() != null && user.getUserTags3().size() > 0) {
            List<UserTag> userTags = user.getUserTags3();
            for (int i = 0; i < userTags.size(); i++) {
                UserTag userTag = userTags.get(i);
                userTag.setSortno(i+1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType("3");
                saveList.add(userTag);
            }
        }

        if (user.getUserTags4() != null && user.getUserTags4().size() > 0) {
            List<UserTag> userTags = user.getUserTags4();
            for (int i = 0; i < userTags.size(); i++) {
                UserTag userTag = userTags.get(i);
                userTag.setSortno(i+1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType("4");
                saveList.add(userTag);
            }
        }
        if (user.getUserTags5() != null && user.getUserTags5().size() > 0) {
            List<UserTag> userTags = user.getUserTags5();
            for (int i = 0; i < userTags.size(); i++) {
                UserTag userTag = userTags.get(i);
                userTag.setSortno(i+1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType("5");
                saveList.add(userTag);
            }
        }

        if (user.getUserTags6() != null && user.getUserTags6().size() > 0) {
            List<UserTag> userTags = user.getUserTags6();
            for (int i = 0; i < userTags.size(); i++) {
                UserTag userTag = userTags.get(i);
                userTag.setSortno(i+1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType("6");
                saveList.add(userTag);
            }
        }

        if (saveList.size()>0) {
            batchSave(saveList);
        }


        if (user.getUserFiles() != null && user.getUserFiles().size() > 0) {
            List<UserFile> saveFileList = new ArrayList<>();
            List<UserFile> userFiles = user.getUserFiles();
            for (int i = 0; i < userFiles.size(); i++) {
                UserFile userFile = userFiles.get(i);
                userFile.setDefaultTime();
                userFile.setUserId(userId);
                saveFileList.add(userFile);
            }
            batchSave(saveFileList);
        }


        if (userRoleChange){
            String sql = "delete from tbl_user_role where userId = :userId";
            Map<String,Object> params = new HashMap<>();
            params.put("userId",userId);
            executeSql(sql,params);

            sql = "insert into tbl_user_role(id,create_date_time,update_date_time,version,deleted,roleId,userId)" +
                    " values(:id,now(),now(),1,0,:roleId,:userId)";

            for (String roleId : roleIds.split(",")) {
                params.put("id",UUID.randomUUID().toString().replace("-",""));
                params.put("roleId",roleId);
                executeSql(sql,params);
            }

            redisDao.delete(userId);
            redisDao.delete(RedisConstant.ROLE_PRE+userId);
            redisDao.delete(RedisConstant.PERMISSION_PRE+userId);
        }

        try {
            User nowUser = getUserById(userId);

            dataaf = new Gson().toJson(nowUser);

            ItemChangeRecord record = new ItemChangeRecord();
            record.setDefaultTime();
            record.setUserid(edituser);
            record.setType("item_change_type_user");
            record.setItemid(userId);
            record.setDatabf(databf);
            record.setDataaf(dataaf);
            record.setName(user.getName());
            record.setSubtype(StringUtils.isEmpty(databf) ? 0 : 1);
            save(record);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public Result editUserTags(UserTagChange userTagChange) throws Exception {
        Result result = new Result();
        String userId = userTagChange.getUserId();
        String edituser = userTagChange.getEdituser();
        User oldUser = getUserById(userId);

        String type = userTagChange.getType();
        String changeType = "家庭成员变更";
        if ("1".equals(type)) {
            changeType = "教育信息变更";
        }else if ("2".equals(type)) {
            changeType = "职称信息变更";
        }else if ("3".equals(type)) {
            changeType = "执业资格变更";
        }else if ("4".equals(type)) {
            changeType = "⼯作履历变更";
        }else if ("5".equals(type)) {
            changeType = "职务信息变更";
        }else if ("6".equals(type)) {
            changeType = "劳动合同变更";
        }

        String databf = new Gson().toJson(oldUser);
        String sql = "update tbl_user set sh='0',shtime=null,reason=null,update_date_time=now(),changetype='"+changeType+"' where id=:userId";
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        executeSql(sql, params);


        sql = "delete from tbl_user_tag where userId=:userId and type=:type";

        params.put("type", type);
        executeSql(sql, params);
        List<UserTag> userTags = userTagChange.getUserTags();
        if (userTags != null && userTags.size() != 0) {
            for (int i = 0; i < userTags.size(); i++) {
                UserTag userTag = userTags.get(i);
                userTag.setSortno(i + 1);
                userTag.setDefaultTime();
                userTag.setUserId(userId);
                userTag.setType(type);
            }
            batchSave(userTags);
        }

        try {
            User nowUser = getUserById(userId);

            String dataaf = new Gson().toJson(nowUser);

            ItemChangeRecord record = new ItemChangeRecord();
            record.setDefaultTime();
            record.setUserid(edituser);
            record.setType("item_change_type_user");
            record.setItemid(userId);
            record.setDatabf(databf);
            record.setDataaf(dataaf);
            record.setSubtype(1);
            save(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    @Override
    public Result editUserDept(List<String> userIds, String deptId,String edituser) throws Exception {
        Result result = new Result();
        String sql = "update tbl_user set dept_id = :deptId where id in (:userIds)";
        Map<String, Object> params = new HashMap<>();
        params.put("userIds", userIds);
        params.put("deptId", deptId);
        executeSql(sql, params);

        return result;
    }

    @Override
    public Result updateUserState(String id, int state, String reason) throws Exception {
        Result response = new Result();
        User user = get(User.class, id);

        if ((StringUtils.isEmpty(user.getSh()) || "0".equals(user.getSh()) || "-1".equals(user.getSh())) && (state == 1 || state == -1)) {
            String sql = "update tbl_user set shtime=now(),sh = :state,reason =:reason where id = :id";
            Map<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("state", state);
            params.put("reason", reason);
            executeSql(sql, params);

        } else {
            response.setSuccess(false);
            response.setMessage("该状态无法审核！");
        }
        return response;
    }

    @Override
    public List<Map<String, Object>> getUserList(String name, String empNo, String sex, String arole, String deptId,String wrDeptId,String sh,String startTime,String endTime, Integer pageNum, Integer pageSize) {
        String sql = "select u.*,o.name deptName,date_format(u.create_date_time,'%Y-%m-%d %H:%i:%S') create_time from tbl_user u left join tbl_org o on o.id = u.dept_id where  1=1 ";
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotEmpty(name)) {
            sql += " and (u.name like :name or u.mobile like :name)";
            params.put("name", "%" + name + "%");

        }

        if (StringUtils.isNotEmpty(empNo)) {
            sql += " and u.empno like :empNo ";
            params.put("empNo", "%" + empNo + "%");

        }

        if (StringUtils.isNotEmpty(arole)) {
            sql += " and u.arole = :arole ";
            params.put("arole", arole);

        }

        if (StringUtils.isNotEmpty(deptId)) {
            sql += " and u.dept_id in (:deptIdList) ";
            params.put("deptIdList", deptId.split(","));

        }else if (StringUtils.isNotEmpty(wrDeptId)) {
            String deptSql = "select p.levelCode from tbl_org o left join tbl_org p on p.id = o.parent_id where o.id = :wrDeptId";
            Map<String, Object> deptParams = new HashMap<>();
            deptParams.put("wrDeptId", wrDeptId);
            String levelCode = getBySql(deptSql, deptParams);
            if (StringUtils.isEmpty(levelCode)) {
                deptSql = "select id from tbl_org order by levelCode asc";
            }else {
                deptSql = "select id from tbl_org where levelCode like '"+levelCode+"%' order by levelCode asc";
            }
            List<String> deptList = findBySql(deptSql);

            sql += " and u.dept_id in (:deptIdList) ";
            params.put("deptIdList", deptList);

        }

        if (StringUtils.isNotEmpty(sex)) {
            sql += " and u.sex = :sex ";
            params.put("sex", sex);

        }

        if (StringUtils.isNotEmpty(sh)) {
            if ("1".equals(sh)) {
                sql += " and u.sh = '1' ";
            }else {
                sql += " and (u.sh = '0' or u.sh = '-1' or u.sh is null or u.sh='') ";
            }

        }
        if (StringUtils.isNotEmpty(startTime)) {
            sql += " and u.create_date_time >= :startTime ";
            params.put("startTime", startTime);

        }

        if (StringUtils.isNotEmpty(endTime)) {
            sql += " and u.create_date_time <= :endTime ";
            params.put("endTime", endTime);

        }

        sql += " order by cast(empNo as SIGNED ) asc,u.id asc ";
        List<Map<String, Object>> list = null;
        if (pageSize != null && pageSize > 0 && pageNum != null && pageNum > 0) {
            list = findMapBySql(sql, params, pageNum, pageSize);
        } else {
            list = findMapBySql(sql, params);
        }
        return list;
    }

    @Override
    public long getUserCount(String name, String empNo, String sex, String arole, String deptId,String wrDeptId,String sh,String startTime,String endTime) throws Exception {
        String cntsql = "select count(*) from tbl_user u where 1=1 ";
        Map<String, Object> cntparams = new HashMap<>();
        if (StringUtils.isNotEmpty(name)) {
            cntsql += " and (u.name like :name or u.mobile like :name) ";
            cntparams.put("name", "%" + name + "%");

        }

        if (StringUtils.isNotEmpty(empNo)) {
            cntsql += " and u.empno like :empNo ";
            cntparams.put("empNo", "%" + empNo + "%");

        }

        if (StringUtils.isNotEmpty(arole)) {
            cntsql += " and u.arole = :arole ";
            cntparams.put("arole", arole);

        }

        if (StringUtils.isNotEmpty(deptId)) {
            cntsql += " and u.dept_id in (:deptIdList) ";
            cntparams.put("deptIdList", deptId.split(","));

        }else if (StringUtils.isNotEmpty(wrDeptId)) {
            String deptSql = "select p.levelCode from tbl_org o left join tbl_org p on p.id = o.parent_id where o.id = :wrDeptId";
            Map<String, Object> deptParams = new HashMap<>();
            deptParams.put("wrDeptId", wrDeptId);
            String levelCode = getBySql(deptSql, deptParams);
            if (StringUtils.isEmpty(levelCode)) {
                deptSql = "select id from tbl_org order by levelCode asc";
            }else {
                deptSql = "select id from tbl_org where levelCode like '"+levelCode+"%' order by levelCode asc";
            }

            List<String> deptList = findBySql(deptSql);

            cntsql += " and u.dept_id in (:deptIdList) ";
            cntparams.put("deptIdList", deptList);

        }


        if (StringUtils.isNotEmpty(sex)) {
            cntsql += " and u.sex = :sex ";
            cntparams.put("sex", sex);

        }

        if (StringUtils.isNotEmpty(sh)) {
            if ("1".equals(sh)) {
                cntsql += " and u.sh = '1' ";
            }else {
                cntsql += " and (u.sh = '0' or u.sh = '-1') ";
            }

        }

        if (StringUtils.isNotEmpty(startTime)) {
            cntsql += " and u.create_date_time >= :startTime ";
            cntparams.put("startTime", startTime);

        }

        if (StringUtils.isNotEmpty(endTime)) {
            cntsql += " and u.create_date_time <= :endTime ";
            cntparams.put("endTime", endTime);

        }

        Long cnt = countBySql(cntsql, cntparams);
        return cnt;
    }

    @Override
    public long getUserCountByAuth(String userId, String name, String empNo, String sex, String arole, String deptId, String sh,String startTime,String endTime) throws Exception {


        String cntsql = "select count(*) from tbl_user u where 1=1 ";
        Map<String, Object> cntparams = new HashMap<>();

        List<String> userDataScope = getUserDataScope(userId);
        if (userDataScope == null || userDataScope.size() == 0) {
            cntsql += " and  u.id = :userId ";
            cntparams.put("userId", userId);
        } else {
            cntsql += " and u.dept_id in (:deptIds) ";
            cntparams.put("deptIds", userDataScope);
        }

        if (StringUtils.isNotEmpty(name)) {
            cntsql += " and (u.name like :name or u.mobile like :name) ";
            cntparams.put("name", "%" + name + "%");

        }

        if (StringUtils.isNotEmpty(empNo)) {
            cntsql += " and u.empno like :empNo ";
            cntparams.put("empNo", "%" + empNo + "%");

        }

        if (StringUtils.isNotEmpty(arole)) {
            cntsql += " and u.arole = :arole ";
            cntparams.put("arole", arole);

        }

        if (StringUtils.isNotEmpty(deptId)) {
            cntsql += " and u.dept_id in (:deptIdList) ";
            cntparams.put("deptIdList", deptId.split(","));

        }


        if (StringUtils.isNotEmpty(sex)) {
            cntsql += " and u.sex = :sex ";
            cntparams.put("sex", sex);

        }

        if (StringUtils.isNotEmpty(sh)) {
            if ("1".equals(sh)) {
                cntsql += " and u.sh = '1' ";
            }else {
                cntsql += " and (u.sh = '0' or u.sh = '-1') ";
            }

        }

        if (StringUtils.isNotEmpty(startTime)) {
            cntsql += " and u.create_date_time >= :startTime ";
            cntparams.put("startTime", startTime);

        }

        if (StringUtils.isNotEmpty(endTime)) {
            cntsql += " and u.create_date_time <= :endTime ";
            cntparams.put("endTime", endTime);

        }

        Long cnt = countBySql(cntsql, cntparams);
        return cnt;
    }

    @Override
    public List<Map<String, Object>> getUserListByAuth(String userId, String name, String empNo, String sex, String arole, String deptId, String sh,String startTime,String endTime, Integer pageNum, Integer pageSize) throws Exception {
        String sql = "select u.*,o.name deptName,date_format(u.create_date_time,'%Y-%m-%d %H:%i:%S') create_time from tbl_user u left join tbl_org o on o.id = u.dept_id where  1=1 ";
        Map<String, Object> params = new HashMap<>();

        List<String> userDataScope = getUserDataScope(userId);
        if (userDataScope == null || userDataScope.size() == 0) {
            sql += " and  u.id = :userId ";
            params.put("userId", userId);
        } else {
            sql += " and u.dept_id in (:deptIds) ";
            params.put("deptIds", userDataScope);
        }

        if (StringUtils.isNotEmpty(name)) {
            sql += " and (u.name like :name or u.mobile like :name)";
            params.put("name", "%" + name + "%");

        }

        if (StringUtils.isNotEmpty(empNo)) {
            sql += " and u.empno like :empNo ";
            params.put("empNo", "%" + empNo + "%");

        }

        if (StringUtils.isNotEmpty(arole)) {
            sql += " and u.arole = :arole ";
            params.put("arole", arole);

        }

        if (StringUtils.isNotEmpty(deptId)) {
            sql += " and u.dept_id in (:deptIdList) ";
            params.put("deptIdList", deptId.split(","));

        }

        if (StringUtils.isNotEmpty(sex)) {
            sql += " and u.sex = :sex ";
            params.put("sex", sex);

        }

        if (StringUtils.isNotEmpty(sh)) {
            if ("1".equals(sh)) {
                sql += " and u.sh = '1' ";
            }else {
                sql += " and (u.sh = '0' or u.sh = '-1' or u.sh is null or u.sh='') ";
            }

        }
        if (StringUtils.isNotEmpty(startTime)) {
            sql += " and u.create_date_time >= :startTime ";
            params.put("startTime", startTime);

        }

        if (StringUtils.isNotEmpty(endTime)) {
            sql += " and u.create_date_time <= :endTime ";
            params.put("endTime", endTime);

        }

        sql += " order by cast(empNo as SIGNED ) asc,u.id asc ";
        List<Map<String, Object>> list = null;
        if (pageSize != null && pageSize > 0 && pageNum != null && pageNum > 0) {
            list = findMapBySql(sql, params, pageNum, pageSize);
        } else {
            list = findMapBySql(sql, params);
        }
        return list;
    }

    public User getUserByLoginName(String loginName) {
        User user = this.get("from User where loginName='" + loginName + "'");
        if (user != null && StrUtil.isNotBlank(user.getDeptId())) {
            Org org = this.get("from Org where id='" + user.getDeptId() + "'");
            user.setDeptLevelCode(org.getLevelCode());
        }
        return user;
    }

    @Override
    public UserAvatar getAvatarByUserId(String userId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        return this.get("from UserAvatar where userId=:userId", params);
    }

    @Override
    public void updateUserAvatar(User user, String dirPath) {
        if (StrUtil.isEmpty(user.getAvatarId()))
            return;
        UserAvatar userAvatar = this.get(UserAvatar.class, user.getAvatarId());
        userAvatar.setUserId(user.getId());
        String src = userAvatar.getSrc();
        File file = new File(dirPath + src);
        String newPath = src.replaceAll("new", user.getName());
        if (file.exists()) {
            file.renameTo(new File(dirPath + newPath));
        }
        userAvatar.setSrc(newPath);
        userAvatar.setName(userAvatar.getName().replaceAll("new", user.getName()));
        this.update(userAvatar);
    }

    @Override
    public Result deleteUser(String userId, String edituser) {

        User user = get(User.class, userId);
        try {

            User oldUser = getUserById(userId);
            String databf = new Gson().toJson(oldUser);
            ItemChangeRecord record = new ItemChangeRecord();
            record.setDefaultTime();
            record.setUserid(edituser);
            record.setType("item_change_type_user");
            record.setItemid(userId);
            record.setDatabf(databf);
            record.setDataaf(null);
            record.setName(user.getName());
            record.setSubtype(2);
            save(record);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String sql = "delete from tbl_user_tag where userId=:userId";
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        executeSql(sql, params);

        sql = "delete from tbl_user where id=:userId";
        executeSql(sql, params);

        return new Result();
    }

    @Override
    public Result deleteUsers(List<String> userIds, String edituser) {
        try {
            for (String userId : userIds) {
                User oldUser = getUserById(userId);
                String databf = new Gson().toJson(oldUser);
                ItemChangeRecord record = new ItemChangeRecord();
                record.setDefaultTime();
                record.setUserid(edituser);
                record.setType("item_change_type_user");
                record.setItemid(userId);
                record.setDatabf(databf);
                record.setDataaf(null);
                record.setName(oldUser.getName());
                record.setSubtype(2);
                save(record);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        String sql = "delete from tbl_user_tag where userId in (:userIds)";
        Map<String, Object> params = new HashMap<>();
        params.put("userIds", userIds);
        executeSql(sql, params);

        sql = "delete from tbl_user where id in (:userIds)";
        executeSql(sql, params);

        return new Result();
    }

    @Override
    public User getUserById(String userId) {
        User user = get(User.class, userId);
        if (user == null) {
            return null;
        }
        String deptId = user.getDeptId();
        if (StrUtil.isNotEmpty(deptId)) {
            Org org = get(Org.class, deptId);
            if (org != null) {
                user.setDeptName(org.getName());
            }
        }
        String sql = "select * from tbl_user_tag where userId=:userId order by type asc,sortno asc,id asc";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", user.getId());
        List<UserTag> userTagList = findBySql(sql, params, UserTag.class);
        if (userTagList != null && userTagList.size() > 0) {
            List<UserTag> userTags0 = null;
            List<UserTag> userTags1 = null;
            List<UserTag> userTags2 = null;
            List<UserTag> userTags3 = null;
            List<UserTag> userTags4 = null;
            List<UserTag> userTags5 = null;
            List<UserTag> userTags6 = null;
            for (UserTag userTag : userTagList) {
                if ("0".equals(userTag.getType())) {
                    if (userTags0 == null) {
                        userTags0 = new ArrayList<>();
                    }
                    userTags0.add(userTag);
                } else if ("1".equals(userTag.getType())) {
                    if (userTags1 == null) {
                        userTags1 = new ArrayList<>();
                    }
                    userTags1.add(userTag);
                } else if ("2".equals(userTag.getType())) {
                    if (userTags2 == null) {
                        userTags2 = new ArrayList<>();
                    }
                    userTags2.add(userTag);
                } else if ("3".equals(userTag.getType())) {
                    if (userTags3 == null) {
                        userTags3 = new ArrayList<>();
                    }
                    userTags3.add(userTag);
                } else if ("4".equals(userTag.getType())) {
                    if (userTags4 == null) {
                        userTags4 = new ArrayList<>();
                    }
                    userTags4.add(userTag);
                } else if ("5".equals(userTag.getType())) {
                    if (userTags5 == null) {
                        userTags5 = new ArrayList<>();
                    }
                    userTags5.add(userTag);
                }else if ("6".equals(userTag.getType())) {
                    if (userTags6 == null) {
                        userTags6 = new ArrayList<>();
                    }
                    userTags6.add(userTag);
                }
            }
            user.setUserTags0(userTags0);
            user.setUserTags1(userTags1);
            user.setUserTags2(userTags2);
            user.setUserTags3(userTags3);
            user.setUserTags4(userTags4);
            user.setUserTags5(userTags5);
            user.setUserTags6(userTags6);
        }

        sql = "select * from tbl_user_file where userId=:userId order by id desc";
        List<UserFile> userFileList = findBySql(sql, params, UserFile.class);
        if (userFileList != null && userFileList.size() > 0) {
            user.setUserFiles(userFileList);
        }

        return user;
    }

    @Override
    public void deleteAuthInRedis(String userId) {
        //缓存SimpleAuthorizationInfo权限
        redisDao.delete(userId);
        redisDao.delete(RedisConstant.ROLE_PRE + userId);
        redisDao.delete(RedisConstant.PERMISSION_PRE + userId);
    }

    @Override
    public String getUserNamesByUserIds(String userIds) {
        StringBuffer buf = new StringBuffer();
        buf.append("select distinct name as name from tbl_user");
        buf.append(" where id in (" + StrUtil.getInStr(userIds) + ")");
        List list = this.findMapBySql(buf.toString());
        return StrUtil.mapToStr(list, "name");
    }

    @Override
    public BaseResponse updatePassword(String loginName, String password) throws Exception {
        BaseResponse result = new BaseResponse();
        String passwordNew = EncryptUtil.getPassword(password, loginName);
        Map<String, Object> params = new HashMap<>();
        params.put("password", passwordNew);
        params.put("loginName", loginName);
        int i = executeHql("UPDATE User set password=:password where loginName=:loginName", params);
        if (i > 0) {

            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            result.setStatus(0);
        } else {
            result.setStatus(1);
            result.setMessage("修改失败！");
        }
        return result;
    }

    @Override
    public List<String> getOrgIdsAndBellow(String userId) throws Exception {
        String sql = "select dept_id from tbl_user where id = :userId";
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        String deptId = getBySql(sql, params);
        if (StringUtils.isNotEmpty(deptId)) {
            List<String> idsOfOrgAndBellow = orgService.getIdsOfOrgAndBellow(deptId, null);
            return idsOfOrgAndBellow;
        }

        return null;
    }

    @Override
    public List<String> getOrgIdsAndBellow(String userId, String orgId) throws Exception {
        if (StringUtils.isNotEmpty(userId)) {
            return getOrgIdsAndBellow(userId);
        }

        if (StringUtils.isNotEmpty(orgId)) {
            List<String> idsOfOrgAndBellow = orgService.getIdsOfOrgAndBellow(orgId, null);
            return idsOfOrgAndBellow;
        }

        return null;
    }

    @Override
    public Map<String, Object> getHigherOrgIds(String userId) throws Exception {
        String sql = "select levelCode,dept_id from tbl_user u left join tbl_org o on o.id=u.dept_id where u.id = :userId";
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        Map<String, Object> userData = getMapBySql(sql, params);
        String levelCode = (String) userData.get("levelCode");
        String deptId = (String) userData.get("dept_id");

        Map<String, Object> data = new HashMap<>();
        List<String> levelCodes = new ArrayList<>();


        int times = levelCode.length() / 6;

        for (int i = 1; i < times; i++) {
            levelCodes.add(levelCode.substring(0, i * 6));
        }
        List<String> deptIds = null;
        if (levelCodes.size() > 0) {
            sql = "select id from tbl_org where levelCode in (:levelCodes)";
            params = new HashMap<>();
            params.put("levelCodes", levelCodes);
            deptIds = findBySql(sql, params, null);
        }
        if (deptIds == null) {
            deptIds = new ArrayList<>();
        }
        if (deptIds.size() == 0) {
            deptIds.add("-2000");
        }
        data.put("deptIds", deptIds);
        return data;
    }

    @Override
    public BaseResponse importUserList(MultipartFile excel) throws Exception {
        //String[] headers = {"序号", "姓名", "手机号", "部门", "岗位","分公司"};
        String[] headers = {"序号", "部门", "岗位", "姓名", "手机号"};
        List<Map<String, Object>> list = ExcelImportUtil.getExcelToListObject(excel, headers);
        /*String sql = "select ID,NAME,DEPARTMENT_ID  from jy_station";
        List<Map<String, Object>> deptS = findMapBySql(sql);
        Map<String, Object> deptMap = new HashMap<>();
        for (Map<String, Object> dept : deptS) {
            String name = (String) dept.get("NAME");
            deptMap.put(name,dept.get("ID"));
        }*/
        List<User> users = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                /* product.setPRODUCTNAME(map.get(headers[0]).toString());
                product.setPRICE(Double.parseDouble(map.get(headers[1]).toString()));
                product.setCOUNT(Integer.parseInt(map.get(headers[3]).toString()));*/
                User sysUser = new User();
                sysUser.setName(map.get(headers[3]).toString());
                sysUser.setMobile(map.get(headers[4]).toString());
                sysUser.setLoginName(map.get(headers[4]).toString());
                String dept = map.get(headers[1]).toString();
                String position = map.get(headers[2]).toString();
                //String cop = map.get(headers[5]).toString();


                //sysUser.setDeptId(cop);
                sysUser.setUserType("0");
                sysUser.setDeleted(0);

                users.add(sysUser);
            }

            batchSave(users);

        }
        BaseResponse response = new BaseResponse();
        response.setStatus(0);
        return response;
    }
}
